package com.manor.main.adapter

import android.view.View
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.makeramen.roundedimageview.RoundedImageView
import com.manor.common.custom.DrawableTextView
import com.manor.common.custom.ItemDecoration
import com.manor.common.custom.SquareImageView
import com.manor.common.interfaces.CommonCallback
import com.manor.common.utils.StringUtil
import com.manor.dynamic.bean.CommunityDynamicBean
import com.manor.dynamic.views.AudioMp3View
import com.manor.main.R
import com.manor.main.activity.UserCenterActivity
import com.blankj.utilcode.util.ConvertUtils
import com.tencent.rtmp.ui.TXCloudVideoView
import java.util.*

class NewDyNamicAdapter (data: MutableList<CommunityDynamicBean>?) : BaseMultiItemQuickAdapter<CommunityDynamicBean, BaseViewHolder>() {


    var requestOptions = RequestOptions().transforms(CenterCrop(), RoundedCorners(8))
    private var listener: NewCircrle? = null

    interface NewCircrle {
        fun clickVideo(container: FrameLayout, videoGroup: View, playView: TXCloudVideoView, img: ImageView, w: Int, h: Int,play:ImageView)
    }

    fun setIOnclickListener(listener: NewCircrle) {
        this.listener = listener
    }

    init {
        addItemType(CommunityDynamicBean.TEXT, R.layout.item_new_square_text)
        addItemType(CommunityDynamicBean.IMG, R.layout.item_new_square_image)
        addItemType(CommunityDynamicBean.VIDEO, R.layout.item_new_square_video)
        addItemType(CommunityDynamicBean.VOICE, R.layout.item_new_square_voice)

    }


    override fun convert(holder: BaseViewHolder, item: CommunityDynamicBean) {
        setPublicView(holder, item)
        when (holder?.itemViewType) {
            CommunityDynamicBean.TEXT -> {

            }
            CommunityDynamicBean.IMG -> {
                val images = item.thumbs
                val imagess = ArrayList<String>()
                val split = item.thumb.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                imagess.addAll(Arrays.asList(*split))
                val rvDynamicImgView = holder.getView<RecyclerView>(R.id.rv_dynamicimg_view)
                val im_pic = holder.getView<SquareImageView>(R.id.im_pic)
                if (images.size == 1) {

                    Glide.with(context).load(if (ishttp(images[0])) images[0] else "http://online.shand2.com/" + images[0])
                            .apply(requestOptions)
                            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
                            .into(im_pic)
                    rvDynamicImgView.visibility = View.GONE
                    im_pic.visibility = View.VISIBLE
                    im_pic.setOnClickListener({
                        (context as UserCenterActivity).lookImgs(imagess as ArrayList<String>, 0, object : CommonCallback<Boolean>() {
                            override fun callback(bean: Boolean?) {
                            }
                        })
                    })
                } else {
                    rvDynamicImgView.visibility = View.VISIBLE
                    im_pic.visibility = View.GONE
                    rvDynamicImgView.setLayoutManager(GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false))
                    val decoration = ItemDecoration(context, 0x00000000, 3f, 3f)
                    decoration.isOnlySetItemOffsetsButNoDraw = true

                    val dynamicImgLocalAdapter = DynamicImgLocalAdapter(R.layout.item_dynamic_img2, images)
                    rvDynamicImgView.setAdapter(dynamicImgLocalAdapter)
                    dynamicImgLocalAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
                        (context as UserCenterActivity).lookImgs(imagess as ArrayList<String>, position, object : CommonCallback<Boolean>() {
                            override fun callback(bean: Boolean?) {
                            }
                        })
                    })
                }
            }
            CommunityDynamicBean.VIDEO -> {
                val mPlayerView = holder.getView<TXCloudVideoView>(R.id.video_view)
                val mContainer: FrameLayout = holder.getView<FrameLayout>(R.id.container)
                val cardview: CardView = holder.getView(R.id.cardview)
                val im_video = holder.getView<ImageView>(R.id.im_video)
                val im_play = holder.getView<ImageView>(R.id.im_play)
                Glide.with(context).load(item.video_thumb).into(im_video)

                val flvUrl = item.getHref()
                mPlayerView.setTag(flvUrl)
                var param = cardview.getLayoutParams() as LinearLayout.LayoutParams
                if (item.width > item.height) {
                    param.width =  ConvertUtils.dp2px( 225f);
                    param.height =   ConvertUtils.dp2px( 170f);

                } else {
                    param.width =  ConvertUtils.dp2px( 170f);
                    param.height =   ConvertUtils.dp2px( 225f);
                }
                cardview.setLayoutParams(param);
                cardview.setOnClickListener({
                    listener?.clickVideo(cardview, mContainer, mPlayerView, im_video, item.width, item.height,im_play)
                })
            }
            CommunityDynamicBean.VOICE -> {
                //  holder.setText(R.id.tv_voice_length, item.getLength() + "s")


                val rl_community_audio = holder.getView<AudioMp3View>(R.id.rl_community_audio)
                rl_community_audio.setTag(item.voice)
                rl_community_audio.setTextLeng(item.getLength())

            }
        }

    }



    private fun setPublicView(helper: BaseViewHolder, item: CommunityDynamicBean) {
        val ivhead = helper.getView<RoundedImageView>(R.id.iv_logo)
        val dTvAge = helper.getView<DrawableTextView>(R.id.tv_age)
        val dTLike = helper.getView<DrawableTextView>(R.id.tv_like)
        val isAuth = helper.getView<ImageView>(R.id.iv_flag)
        val isLove = helper.getView<ImageView>(R.id.iv_love)
        val ivDaRen = helper.getView<ImageView>(R.id.iv_daren)
        val ivGuiZu = helper.getView<ImageView>(R.id.iv_guizu)
        val iv_youzhi = helper.getView<ImageView>(R.id.iv_youzhi)
        val im_gd = helper.getView<ImageView>(R.id.im_gd)
        val tv_tip = helper.getView<TextView>(R.id.tv_tip)
//        val ff = helper.getView<LinearLayout>(R.id.ff)
//        ff.setBackgroundResource(0)

        tv_tip.visibility = View.GONE
        // helper.getView<FrameLayout>(R.id.ff).setBackground(gaussianBlur(helper.getView(R.id.ff)))

        //男女图标背景
        if (item.userinfo != null) {
            if (item.userinfo.sex == "1") {
                dTvAge.leftDrawable = context.getDrawable(R.mipmap.gender_nan)
                helper.getView<View>(R.id.ll_city_genderbg).background = context.getDrawable(R.drawable.shape_item_city_bg)
            } else {
                dTvAge.leftDrawable = context.getDrawable(R.mipmap.gender_nv)
                helper.getView<View>(R.id.ll_city_genderbg).background = context.getDrawable(R.drawable.shape_item_city_bg)
            }
        }
        //是否点赞
        if ("1" == item.islike) {
            dTLike.leftDrawable = context.getDrawable(R.mipmap.icon_up)
        } else if ("0" == item.islike) {
            dTLike.leftDrawable = context.getDrawable(R.mipmap.icon_unup)
        }
        //是否关注
        if (1 == item.isattent) {
            Glide.with(context).load(context.getDrawable(R.mipmap.icon_heart)).into(isLove)
        } else if (0 == item.isattent) {
            Glide.with(context).load(context.getDrawable(R.mipmap.icon_heart_gray)).into(isLove)
        }

        //是否优质
        if (StringUtil.isNotEmpty(item.userinfo.quality)) {
            Glide.with(context).load(item.userinfo.quality).into(iv_youzhi)
            iv_youzhi.visibility = View.VISIBLE
        } else {
            iv_youzhi.visibility = View.GONE
        }
        //是否认证
        if ("1" == item.userinfo.isauth) {
            Glide.with(context).load(item.userinfo.immortal).into(isAuth)
            isAuth.visibility = View.VISIBLE
        } else {
            isAuth.visibility = View.GONE
        }
        //是否达人
        if (StringUtil.isNotEmpty(item.userinfo.level_icon)) {
            Glide.with(context).load(item.userinfo.level_icon).into(ivDaRen)
            ivDaRen.visibility = View.VISIBLE
        } else {
            ivDaRen.visibility = View.GONE
        }
        //是否贵族
        if (StringUtil.isNotEmpty(item.userinfo.gzu_icon)) {
            Glide.with(context).load(item.userinfo.gzu_icon).into(ivGuiZu)
            ivGuiZu.visibility = View.VISIBLE
        } else {
            ivGuiZu.visibility = View.GONE
        }
        helper.setText(R.id.tv_name, item.userinfo.user_nickname)
                .setText(R.id.tv_age, item.userinfo.age.toString())
                .setText(R.id.tv_datetime, item.datetime)
                .setText(R.id.tv_city, item.city)
                .setText(R.id.tv_like, item.likes)
                .setText(R.id.tv_browse, "浏览" + item.over_num + "次")
                .setText(R.id.tv_comment, item.comments)
        addChildClickViewIds(R.id.tv_tip, R.id.tv_forward, R.id.tv_like, R.id.iv_love, R.id.iv_logo, R.id.tv_comment, R.id.rl_community_audio)
        Glide.with(context).load(item.userinfo.avatar).apply(RequestOptions.bitmapTransform(CircleCrop())).into(ivhead)
        if ("" != item.title) {
            val tv_title = helper.getView<TextView>(R.id.tv_title)
            tv_title.text = item.title + ""
            tv_title.visibility = View.VISIBLE
        } else {
            helper.getView<View>(R.id.tv_title).visibility = View.GONE
        }


    }


    internal inner class DynamicImgLocalAdapter(layoutResId: Int, data: MutableList<String>) : BaseQuickAdapter<String, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: String) {
            val ivImg = helper.getView<ImageView>(R.id.img)
            val lp = RelativeLayout.LayoutParams(ivImg.layoutParams)
            lp.setMargins(6, 6, 6, 6)
            val op = RequestOptions()
            op.transform(CenterCrop(), RoundedCorners(8))
            ivImg.layoutParams = lp

            Glide.with(context).load(if (ishttp(item)) item else "http://online.shand2.com/$item")
                    .apply(op)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
                    .into(ivImg)

        }
    }

    private fun ishttp(str: String): Boolean {
        val msg = str.substring(0, 4)
        return if (msg == "http") {
            true
        } else {
            false
        }
    }


}